import axios from 'axios'
import { Notify, Dialog } from 'vant'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    console.error(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data

    const message = res.message

    // 如果自定义 code 不为 0，则认为此次请求有问题
    if (res.code !== 0) {
      Notify({ type: 'warning', message })

      // 401: Illegal token;
      if (res.code === 401) {
        // 重新登陆
        Dialog.confirm({
          title: '退出确认',
          message: '您的登陆状态已过期，是否要重新登陆'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.error(error) // for debug
    return Promise.reject(error)
  }
)

export default service
